package com.zm.shop.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zm.shop.common.entity.GoodsEntity;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl {

    @Autowired  //导入ES链接
    private RestHighLevelClient client;

    @Value("${es.index}") //添加ES索引
    private String indexName;

    @Value("${es.type}")  //添加ES索引类型
    private String typeName;


    public void addGoods(String goodsEntityJSON) throws IOException {
        //JSON转对象
        GoodsEntity goodsEntity = JSON.parseObject(goodsEntityJSON, GoodsEntity.class);
        //创建请求 并且编号
        IndexRequest request=new IndexRequest(indexName,typeName,goodsEntity.getId()+"");
        //放入数据
        request.source(goodsEntityJSON, XContentType.JSON);
        //插入到ES
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        //输出结果
        System.out.println("插入成功");
    }

    public List<Map<String,Object>> search(Map<String, Object> param) throws IOException {

        //获取数据
        String keyword = (String) param.get("keyword");
        //获取排序字段
        String psort = (String)param.get("psort");
        //创建请求
        SearchRequest request=new SearchRequest(indexName);
        request.types(typeName);

        //设置查询条件
        SearchSourceBuilder builder=new SearchSourceBuilder();
        if (StringUtils.isEmpty(keyword)){
            builder.query(QueryBuilders.matchAllQuery()); //全查询
        }else{
            builder.query(QueryBuilders.multiMatchQuery(keyword, "gname", "gdesc")); //匹配查询
        }
        //高亮条件
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("gname",10)
                .preTags("<font color='red'>")
                .postTags("</font>");
        builder.highlighter(highlightBuilder);
        //排序规则
        if(!StringUtils.isEmpty(psort)){
            // 设置排序规则
            switch (psort) {
                case "1":
                    builder.sort("id", SortOrder.ASC);
                    break;
                case "2":
                    builder.sort("stock", SortOrder.DESC);
                    break;
                case "3":
                    builder.sort("gprice", SortOrder.ASC);
                    break;
                case "4":
                    builder.sort("gprice", SortOrder.DESC);
                    break;
                default:break;
            }
        }
        //放入数据
        request.source(builder);
        //查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //输出结果
        System.out.println("response:---"+response);
        // 5.获取结果集(一个匹配结果，几个高亮结果，需要将高亮结果添加到匹配结果里)
        List<Map<String, Object>> goodsMapList = new ArrayList<>();

        //获取查询数据
        SearchHit[] hits = response.getHits().getHits();
        for (int i=0;i<hits.length;i++){
            Map<String, Object> sourceAsMap = hits[i].getSourceAsMap();
            Map<String, HighlightField> highlightFields = hits[i].getHighlightFields();
            if (!highlightFields.isEmpty() && highlightFields.get("gname") != null) {//判断高亮字段不为空
                Text text = highlightFields.get("gname").getFragments()[0];
                String s = text.toString();
                sourceAsMap.put("gname", s); //把高亮字段覆盖原来的gname
            }
            goodsMapList.add(sourceAsMap); //放入新集合里
        }

        return goodsMapList;
    }

}
